var G_STATUS_MAP = {
		"PO_STATUS_NEW" : "POS000001",
		"PO_STATUS_FULLY_INVOICED" : "POS000002",
		"PO_STATUS_PARTIALLY_INVOICED" : "POS000003",
		"PO_STATUS_CANCELLED" : "POS000004",
		"PO_STATUS_FAILED" : "POS000005",
		
		"INV_STATUS_NEW": "IVS000001",
		"INV_STATUS_ACCEPTED" : "IVS000002",
		"INV_STATUS_REJECTED" : "IVS000003",
		"INV_STATUS_FAILED" : "IVS000004",
		"INV_STATUS_FULLY_PAID" : "IVS000005",
		"INV_STATUS_PARTIALLY_PAID" : "IVS000005",
		
		"CMO_STATUS_NEW" : "CMS000001",
		"CMO_STATUS_ACCEPTED" : "CMS000002",
		"CMO_STATUS_REJECTED" : "CMS000003",
		"CMO_STATUS_FAILED" : "CMS000004"
}

jQuery(document).ready(function() {
	//Setup login values.
	dwr.util.setValue('w_uname', usrfname + " " + usrlname);
	dwr.util.setValue('w_comp_name',usrcompany_name);
	dwr.util.setValue('w_act_type',preference);
	if(llt != null && llt != "" && llu != null && llu != ""){
		dwr.util.setValue('w_last_logininfo', 'Last Log In : ' + llu + " on " + new Date(llt));
	}else{
		dwr.util.setValue('w_last_logininfo', '');
	}
	
	//Setup user profile.
	loadUserProfile();
	
	//Setup user company cache.
	setup_usercompcache(success_getLoggedInUserCompany);
	
	//
	comp_authusrs_cache = {};
	render_jqUserTable();
	fetch_uomcurdetails();
});


function ysn_dwrerror_handler(msg, ex){
	showusrmessage("<span class='redtxt'>An error ocurred while processing: " 
			+ "<br>- Message: " + msg 
			+ "<br>- Error from Server: " + ex.message + "</span>;")
	
}



function format_date(d) {
	var m_names = new Array("January", "February", "March", "April", "May",
			"June", "July", "August", "September", "October", "November",
			"December");
	var curr_date = d.getDate();
	var curr_month = d.getMonth() + 1;
	var curr_year = d.getFullYear();
	// return curr_date + "-" + m_names[curr_month] + "-" + curr_year;
	return (curr_month < 10 ? "0" + curr_month + "" : curr_month) + "/"
			+ (curr_date < 10 ? "0" + curr_date + "" : curr_date) + "/"
			+ curr_year;
}

function bc_link_clicked(id){
	
	jQuery("ul#bc_links li").each(function() {
		var curid  = this.id;
		c_showhide_links(curid,id);
	});
	
	jQuery("ul#sc_links li").each(function() {
		var curid  = this.id;
		c_showhide_links(curid,id);
	});
	/*if(lnk== 'PO_SENT'){
		jQuery('#bc_links').html("<li class='selected'>Purchase Order Sent |</li><li><a href='#'>Invoice Received</a> |</li><li><a href='#'>Credit Memo Received</a> |</li><li><a href='#'>Payment Sent</a></li>");
		
	}else if()*/
}

function c_showhide_links(curid,id){
	if (curid==id) {
		jQuery('#' + curid + "_a").removeClass('showlist');
		jQuery('#' + curid + "_a").addClass('hide');
		jQuery('#' + curid + "_sp").removeClass('hide');
		jQuery('#' + curid + "_sp").addClass('showlist visitedbold');
		jQuery('#ctx_' + curid + "_tbldiv").removeClass('hide');
		jQuery('#ctx_' + curid + "_tbldiv").addClass('show');
	}else{
		jQuery('#' + curid + "_a").removeClass('hide');
		jQuery('#' + curid + "_a").addClass('showlist');
		jQuery('#' + curid + "_sp").removeClass('showlist');
		jQuery('#' + curid + "_sp").addClass('hide');
		jQuery('#ctx_' + curid + "_tbldiv").removeClass('show');
		jQuery('#ctx_' + curid + "_tbldiv").addClass('hide');
	}
}

function isEmptyString(s) {
	if (typeof s == "undefined") {
		return true;
	}

	if (s == null) {
		return true;
	}
	if (s == "") {
		return true;
	}
	if (s == " ") {
		return true;
	}
	if (s == "&nbsp;" || s == "&NBSP;" ) {
		return true;
	}

	return false;
}

function format_currency(num) {
    num = isNaN(num) || isEmptyString(num) ? 0.00 : num;
    return parseFloat(num).toFixed(2) + "";
}



function c_get_notifications(isBuyer){
	if(!isEmptyString(llt) && "NaN" != llt  && !isEmptyString(usrcompany_id)){
		var dwrCallMetaData = {
				callback : success_getnotifications,
				exceptionHandler : ysn_dwrerror_handler,
				timeout : 100000,
				errorHandler : ysn_dwrerror_handler
			};

		if(preference == "Buyer"){
			DWR_UserManagement.getNotificationsForUser(usrcompany_id,new Date(llt), isBuyer, dwrCallMetaData);
		}else {
			DWR_UserManagement.getNotificationsForUser(usrcompany_id,new Date(llt), isBuyer, dwrCallMetaData);
		}
	}	
}


function success_getnotifications(dwrresp){
	var t_prefix = '';
	if(preference == "Buyer"){
		t_prefix = "bc_notifications";
	}else {
		t_prefix = "sc_notifications";
	}
	
	dwr.util.setValue(t_prefix + '_header','');
	jQuery('#' + t_prefix + '_throbber').removeClass('notif_throbberOn').addClass('notif_throbberOff');
	
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null ){
			var resp = dwrresp.objRespOrError;
			var msgs = new Array();
			if(!isEmptyString(resp['SUPPLIER_PO'])){
				msgs.push(resp['SUPPLIER_PO']);
			}
			if(!isEmptyString(resp['SUPPLIER_PAYMENTS'])){
				msgs.push(resp['SUPPLIER_PAYMENTS']);
			}
			if(!isEmptyString(resp['BUYER_MEMOS'])){
				msgs.push(resp['BUYER_MEMOS']);
			} if(!isEmptyString(resp['BUYER_INVOICES'])){
				msgs.push(resp['BUYER_INVOICES']);
			}
			
			if(msgs.length > 0){
				var len = msgs.length;
				dwr.util.setValue(t_prefix + '_header', len + ' new message(s)');
				for(var i=0;i<len;i++){
					var id = (i + 1 ) + "";
					dwr.util.cloneNode(t_prefix + "_pattern", {idSuffix:id});
					dwr.util.setValue(t_prefix + "_msg" + id, "- " + msgs[i]);
					jQuery('#'+t_prefix + "_pattern"+id).attr('style','display:table-row');
				}
			}else{
				dwr.util.cloneNode(t_prefix + "_pattern", {idSuffix:"1"});
				dwr.util.setValue(t_prefix + "_msg" + "1", "No new messages");
				dwr.util.setValue(t_prefix + '_header','No new messages');
				jQuery('#'+t_prefix + "_pattern"+"1").attr('style','display:table-row');
			}
		}else{
			dwr.util.cloneNode(t_prefix + "_pattern", {idSuffix:"1"});
			dwr.util.setValue(t_prefix + "_msg" + "1", "No new messages");
			dwr.util.setValue(t_prefix + '_header','No new messages');
			jQuery('#'+t_prefix + "_pattern"+"1").attr('style','display:table-row');
		}
	}
}

function hideAllScreen(){
	jQuery('#dashBoradContiner').addClass('hide').removeClass('show');
	jQuery('#companyProfileConatiner').addClass('hide').removeClass('show');
	jQuery('#userProfileContainer').addClass('hide').removeClass('show');
	jQuery('#supplierManagementConatiner').addClass('hide').removeClass('show');
	jQuery('#poContainer').addClass('hide').removeClass('show');
	jQuery('#poListContainer').addClass('hide').removeClass('show');
	jQuery('#poDetailContainer').addClass('hide').removeClass('show');
	jQuery('#newPaymentContainer').addClass('hide').removeClass('show');
	jQuery('#invContainer').addClass('hide').removeClass('show');
	
	
}

var	selectedMenu = "homeMenu";
var	selectedSubMenu = "homeSubMenu";		
function setMenu(menuId,subMenuId){
	jQuery('#'+selectedSubMenu).addClass('hide').removeClass('show');
	jQuery('#'+selectedMenu).addClass("select").removeClass("active");
	
	jQuery('#'+subMenuId).addClass('show').removeClass('hide');
	jQuery('#'+menuId).addClass("active").removeClass("select");
	selectedMenu = menuId;
	selectedSubMenu = subMenuId;
	
	if(menuId == 'profileMenu'){
		showUserProfile();
	}
	
	if(menuId == 'homeMenu'){
		showDashboard(); //buyer context
	}
	
	if(menuId == 'poMenu'){
		showNewPOScreen(); //buyer context
	}
	
}

function showUserProfile(){
	hideAllScreen();
	jQuery('#userProfileContainer').addClass('show').removeClass('hide'); //first screen of user profile
	loadUserProfile();
}

function showCompanyProfile(){
	hideAllScreen();
	jQuery('#companyProfileConatiner').addClass('show').removeClass('hide');
	loadCompanyInfo();
}

function showDashboard(){
	hideAllScreen();
	jQuery('#dashBoradContiner').addClass('show').removeClass('hide'); //first screen of user profile
}
function showSupplierManagement(){
	hideAllScreen();
	jQuery('#supplierManagementConatiner').addClass('show').removeClass('hide'); //first screen of user profile
}

jQuery(function() {
	jQuery( "#tabs" ).tabs().show(0);
	jQuery( "#supplierManagementConatiner" ).tabs();
	jQuery( "#supplierManagementConatiner" ).tabs();
	jQuery('#from_company_register').ketchup();
	jQuery('#from_user_register').ketchup();
	jQuery('#form_addcomploc').ketchup();
	
});

function validateForm(){
	jQuery('#from_addcomp').ketchup();
}




var usr_comp_cache = null;
var usr_profile_cache = null;

function setup_usercompcache(handlerfunc){
	var dcmd = {
			callback : handlerfunc,
			exceptionHandler : ysn_dwrerror_handler,
			timeout : 100000,
			errorHandler : ysn_dwrerror_handler
		};

	DWR_PurchaseOrders.findCompanyById(usrcompany_uid,
			dcmd);
}

function success_getLoggedInUserCompany(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null) {
			usr_comp_cache = dwrresp.objRespOrError;
			getUserGroup();
			getAuthorizedUsersForCompany();
			init_pmtterms();
			init_noti_prefs();
			
		}
	}
}

var ketchupObj = jQuery.ketchup;

var common_msgdlg = null;
function showusrmessage(msg){
	if(common_msgdlg == null){
		common_msgdlg = jQuery( "#modal-dialog-commonmsg" ).dialog({
		
			height: 'auto',
			width: 300,
			modal: true,
			autoOpen: false 
		});
	}
	
	dwr.util.setValue('msg_spn',msg,{escapeHtml: false});
	jQuery( "#modal-dialog-commonmsg" ).dialog('open');
}



var poAttachmentArray =  new Array();






function fetch_uomcurdetails(){
	var dcmd1 = {
			callback : success_fetchuom,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null
		};
	DWR_PurchaseOrders.getAllUnitOfMeasures(dcmd1);
	
	var dcmd2 = {
			callback : success_fetchcur,
			exceptionHandler : null,
			timeout : 100000,
			errorHandler : null
		};
	
	
	DWR_PurchaseOrders.getAllCurrencyCodes(dcmd2);
}
var uom_cache = null;
function success_fetchuom(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			uom_cache = dwrresp.objRespOrError;
		}
	}
}

var cur_cache = null;
function success_fetchcur(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			cur_cache = dwrresp.objRespOrError;
		}
	}
}

function toggleHeaderDiv(obj){
	jQuery(obj).toggleClass('selected');	  
	jQuery(obj).next().slideToggle('fast');
}

function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}